'usr strict';

let express = require('express');
let crypto = require('crypto');
let router = express.Router();
let renderCache = require('./renderCache');
let pdfRender = require('../render/PDFRender');

router.get('/', function (req, res, next) {
  res.render('index', {
    title: 'PDFRender.'
  });
});

router.post('/render', function (req, res, next) {
  let body = req.body;
  let md5 = crypto.createHash('md5');
  let key = md5.update(JSON.stringify(body)).digest('hex');
  renderCache.addItem(key, body);
  res.end(JSON.stringify({
    success: true,
    key
  }));
});

router.get('/render', function (req, res, next) {
  let key = req.query.key;
  let body = renderCache.getItem(key);
  if (!body) {
    res.writeHead(200, { 'Content-Type': 'text/html;charset=utf-8' });
    res.end('渲染地址无效或已失效,请重新生成!');
    return;
  }
  new pdfRender().render(res, body.data, body.style);
});

module.exports = router;